import { Injectable, Logger, OnApplicationBootstrap } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { DataSource, In, Not, Repository } from "typeorm";
import { PermissionEntity } from "src/entity";
import { ConfigService } from "@nestjs/config";
import { getDefinePermissions } from "src/decorator";
import { PaginationData } from "src/common/model";
import { PermissionQueryDto } from "src/dto/permission";
import { pagination } from "src/common/pagination.query";

@Injectable()
export class PerimssionService implements OnApplicationBootstrap {
    private readonly logger = new Logger(PerimssionService.name);

    constructor(
        private readonly dataSource: DataSource,
        @InjectRepository(PermissionEntity) private readonly permissionRepository: Repository<PermissionEntity>,
        private readonly configService: ConfigService,
    ) {}

    onApplicationBootstrap() {
        return this.initPermission();
    }

    async initPermission() {
        const definePerms = getDefinePermissions();

        this.logger.log(`all permission code: ${JSON.stringify(definePerms.map((item) => item.code))}`);

        await this.permissionRepository
            .createQueryBuilder()
            .insert()
            .values(definePerms.map((item) => ({ id: null, ...item })))
            .orUpdate(["name", "description"], ["code"])
            .execute();

        await this.permissionRepository.delete({
            code: Not(In(definePerms.map((item) => item.code))),
        });
    }

    async query(dto: PermissionQueryDto) {
        this.logger.log(`requset query permissions`);
        const qb = this.permissionRepository.createQueryBuilder("perm");
        if (dto.where?.code) {
            qb.where("perm.code LIKE :code", {
                code: `%${dto.where.code}%`,
            });
        }
        return pagination(qb, dto);
    }
}
